import remoteSearchBatchCodeInput from '../remote-search-batch-code-input';
import {
	cottonPpfCottonBlendingCreate,
	cottonPpfCottonBlendingGet, cottonPpfCottonBlendingGetVersion,
	cottonPpfCottonBlendingUpdate
} from '../../../../../../api/production/productConfigCotton';
import { formatDate } from '../../../../../../utils/jk/jk-tool';
import checkboxProductDialog from '../../../../order/components/checkbox-product-dialog';
import remoteSearchProductInput from '../../../../order/components/remote-search-product-input';
import remoteSearchEmpInput from '../../../../order/components/remote-search-emp-input';
import jkSaveButton from '../../../../../jk-components/jk-save-button';
import jkUpdateButton from '../../../../../jk-components/jk-update-button';
export default {
	components: { jkSaveButton, jkUpdateButton, remoteSearchProductInput, remoteSearchEmpInput, remoteSearchBatchCodeInput, checkboxProductDialog },
	props: {
		loading: {
			type: Boolean,
			default: false
		},
		pageType: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			prefix: 'cotton:ppfCottonBlending',
			apiItem: {
				'save': cottonPpfCottonBlendingCreate,
				'update': cottonPpfCottonBlendingUpdate,
				'get': cottonPpfCottonBlendingGet
			},
			showLoading: false,
			checkboxProductDialogState: false,
			tableData: [],
			updateAuditLoading: false,
			saveAuditLoading: false,
			saveBtnLoading: false,
			workshopList: [],
			saveDialogState: false,
			ruleForm: {
				'code': '系统自动生成',
				'date': '',
				'auditState': 0,
				'batchId': null,
				'batchCode': '',
				'workshopId': null,
				'workshopCode': '',
				'workshopName': '',
				'userId': null,
				'userCode': '',
				'userName': '',
				'processCode': '',
				'processId': null,
				'processName': '',
				'productCode': '',
				'productId': null,
				'productModels': '',
				'productName': ''
			},
			rules: {
				meters: [{ required: true, trigger: 'change' }],
				moistureRegain: [{ required: true, trigger: 'change' }],
				gramWeight: [{ required: true, trigger: 'change' }],
				userId: [{ required: true, trigger: 'change' }],
				efficiencyPercent: [{ required: true, trigger: 'change' }],
				dailyYield: [{ required: true, trigger: 'change' }],
				specEmpId: [{ required: true, trigger: 'change' }],
				productId: [{ required: true, trigger: 'change' }],
				workshopId: [{ required: true, trigger: 'change' }],
				batchId: [{ required: true, trigger: 'change' }],
				code: [{ required: true, trigger: 'change' }],
				date: [{ required: true, trigger: 'change' }]
			}
		};
	},
	methods: {
		onConfirmBtnOfCheckBoxProductDialog(arr) {
			arr.forEach(x => {
				this.tableData.push({
					productId: x.id,
					productCode: x.code,
					productName: x.name,
					productModels: x.models,
					unitId: x.unitId,
					unitCode: x.unitCode,
					unitName: x.unitName,
					ratio: parseInt(10 + Math.random() * 10)
				});
			});
			this.checkboxProductDialogState = false;
		},
		onVisibleChangeOfCheckBoxProductDialog(e) {
			this.checkboxProductDialogState = e;
		},
		onAddBtn() {
			this.checkboxProductDialogState = true;
		},
		onSelectEmpChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'userId', e.id);
				this.$set(this.ruleForm, 'userCode', e.code);
				this.$set(this.ruleForm, 'userName', e.name);
			}
		},
		onSelectProductChange(e) {
			if (Object.keys(e).length) {
				this.setProductDependentData(e);
			}
		},
		onSelectBatchChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchId', e.id);
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
				this.getVersion();
			}
		},
		getVersion() {
			if (this.ruleForm.workshopId && this.ruleForm.batchCode && this.ruleForm.productId) {
				return cottonPpfCottonBlendingGetVersion({
					productId: this.ruleForm.productId,
					batchId: this.ruleForm.batchId,
					workshopId: this.ruleForm.workshopId
				}).then(res => {
					if (res.data.status === 200) {
						this.$set(this.ruleForm, 'version', res.data.res);
					}
				});
			}
		},
		setProductDependentData(e) {
			this.$set(this.ruleForm, 'batchId', null);
			this.$set(this.ruleForm, 'batchCode', '');
			this.$set(this.ruleForm, 'productId', e.id);
			this.$set(this.ruleForm, 'productCode', e.code);
			this.$set(this.ruleForm, 'productName', e.name);
			this.$set(this.ruleForm, 'productModels', e.models);
		},
		defaultRowData() {
			return {
				processId: null,
				processCode: '',
				processName: ''
			};
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.workshopCode = this.workshopList.find(x => x.id === params.workshopId).code;
			params.workshopName = this.workshopList.find(x => x.id === params.workshopId).name;
			params.ppfCottonBlendingItemList = JSON.parse(JSON.stringify(this.tableData));
			return params;
		},
		onConfirmBtn() {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.createAndUpdateRequest();
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		createAndUpdateRequest() {
			this.saveBtnLoading = true;
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				this.apiItem.save(this.getParamData()).then(res => {
					this.saveBtnLoading = false;
					if (res.data.status === 200) {
						this.$tipsBar(this, 'save');
						this.onJump(res.data.res);
					} else if (res.data.status === 1010011002) {
						console.log('重复', res.data);
						this.$confirm(`版本号"${this.ruleForm.version}"已经被使用，点击"确定"获取新的版本号。`, `版本重复`, { type: 'warning' }).then(() => {
							this.exportLoading = true;
						}).then(() => {
							this.getVersion();
						}).catch(() => {});
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.getParamData()).then(res => {
				this.saveBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.getDependentData();
				}
			});
		},
		getParamData() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.workshopCode = this.workshopList.find(x => x.id === params.workshopId).code;
			params.workshopName = this.workshopList.find(x => x.id === params.workshopId).name;
			params.ppfCottonBlendingItemList = JSON.parse(JSON.stringify(this.tableData));
			return params;
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getDetailRequest() {
			return this.apiItem.get({ id: this.dataId }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					this.ruleForm = resData;
					this.tableData = resData.ppfCottonBlendingItemList || [];
				}
			});
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'ProductConfigCotton'
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editProductConfigCotton',
				query: {
					id: id
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.workshopList = this.$store.state.user.userWorkshop.workshopList;
			if (!this.dataId) {
				this.$set(this.ruleForm, 'date', formatDate(Date.now()));
				this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
				this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
				this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
			}
			if (this.dataId) await this.getDetailRequest();
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate(['productId', 'userId', 'batchId']);
			});
			this.showLoading = false;
		},
		clearCacheData() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	}
};
